const mongoose = require('mongoose');

const ENV = process.env.NODE_ENV || 'development';

// 根据环境选择不同的数据库
const DB_NAME = {
    'development': 'zhimi_dev',
    'test': 'zhimi_test',
    'production': 'zhimi_prod'
}[ENV];

// 修改连接字符串，添加authSource=admin
const MONGODB_URI = process.env.MONGODB_URI || 
    'mongodb://longwei:19931993Lw%40@106.55.6.248:27017/kankankan?authSource=admin';

// 设置mongoose配置
mongoose.set('debug', true);
mongoose.set('strictQuery', false);  // 添加这行以消除警告

// 创建连接
const connectDB = async () => {
    try {
        await mongoose.connect(MONGODB_URI, {
            useNewUrlParser: true,
            useUnifiedTopology: true,
            serverSelectionTimeoutMS: 5000,
            retryWrites: true,
            w: 'majority'
        });
        console.log('MongoDB连接成功');

        // 监听连接事件
        mongoose.connection.on('error', err => {
            console.error('MongoDB连接错误:', err);
        });

        mongoose.connection.on('disconnected', () => {
            console.log('MongoDB连接断开，尝试重连...');
            connectDB();
        });

    } catch (err) {
        console.error('MongoDB连接失败:', err);
        process.exit(1);
    }
};

// 导出连接函数和mongoose实例
module.exports = {
    connectDB,
    mongoose
}; 